package xuan.mall.system.infrastructure.security.service;

import cn.hutool.core.bean.BeanUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import xuan.mall.system.domain.entity.MallUserDetails;
import xuan.mall.system.domain.entity.Role;
import xuan.mall.system.domain.entity.User;
import xuan.mall.system.domain.repository.RoleRepository;
import xuan.mall.system.domain.repository.UserRepository;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author: rongxuanzhou
 * @create: 2025/6/1
 * @Description:
 */
@Service
@RequiredArgsConstructor
public class MallUserDetailsService implements UserDetailsService {

    private final UserRepository userRepository;
    private final RoleRepository roleRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        if (user != null) {
            MallUserDetails mallUserDetails = BeanUtil.copyProperties(user, MallUserDetails.class);

            Set<GrantedAuthority> authorities = new HashSet<>(); // 角色集合
            List<Role> roles = roleRepository.findRolesByUserId(mallUserDetails.getId());
            for (Role role : roles) {
                authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
            }
            mallUserDetails.setAuthorities(authorities);
            return mallUserDetails;
        }
        return null;
    }
}
